#!/bin/bash

# 设置颜色和样式
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
CYAN='\033[0;36m'
BOLD='\033[1m'
NC='\033[0m'

# 进度条函数
show_progress() {
    local width=50  # 固定宽度为50个字符
    local progress=0
    
    echo -n "["
    for ((i=0; i<width; i++)); do
        echo -n " "
    done
    echo -n "] 0%"
    
    for ((i=0; i<=width; i++)); do
        progress=$((i * 100 / width))
        echo -ne "\r["
        for ((j=0; j<i; j++)); do
            echo -n "▓"
        done
        for ((j=i; j<width; j++)); do
            echo -n " "
        done
        echo -n "] $progress%"
        sleep 0.1
    done
    echo
}

# 显示欢迎界面
clear
echo -e "${CYAN}${BOLD}"
cat << "EOF"
███╗   ██╗ █████╗ ██████╗  ██████╗ █████╗ ████████╗
████╗  ██║██╔══██╗██╔══██╗██╔════╝██╔══██╗╚══██╔══╝
██╔██╗ ██║███████║██████╔╝██║     ███████║   ██║   
██║╚██╗██║██╔══██║██╔═══╝ ██║     ██╔══██║   ██║   
██║ ╚████║██║  ██║██║     ╚██████╗██║  ██║   ██║   
╚═╝  ╚═══╝╚═╝  ╚═╝╚═╝      ╚═════╝╚═╝  ╚═╝   ╚═╝   
EOF
echo -e "${NC}"
echo -e "${BLUE}${BOLD}QQ机器人部署系统 - 高级安装向导${NC}\n"

# 检查 Docker 是否安装
echo -e "${CYAN}[1/5]${NC} 检查系统环境..."
if ! command -v docker &> /dev/null; then
    echo -e "${YELLOW}Docker 未安装，正在安装...${NC}"
    
    # 更新包列表
    apt-get update
    
    # 安装必要的包
    apt-get install -y \
        apt-transport-https \
        ca-certificates \
        curl \
        gnupg \
        lsb-release

    # 添加阿里云的 Docker GPG 密钥
    curl -fsSL https://mirrors.aliyun.com/docker-ce/linux/ubuntu/gpg | gpg --dearmor -o /usr/share/keyrings/docker-archive-keyring.gpg

    # 添加阿里云的 Docker 仓库
    echo \
        "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/docker-archive-keyring.gpg] https://mirrors.aliyun.com/docker-ce/linux/ubuntu \
        $(lsb_release -cs) stable" | tee /etc/apt/sources.list.d/docker.list > /dev/null

    # 更新包列表
    apt-get update

    # 安装 Docker
    apt-get install -y docker-ce docker-ce-cli containerd.io

    # 配置 Docker 镜像加速
    mkdir -p /etc/docker
    cat > /etc/docker/daemon.json <<EOF
{
    "registry-mirrors": [
        "https://docker.1ms.run",
        "https://mirror.ccs.tencentyun.com",
        "https://hub-mirror.c.163.com",
        "https://mirror.baidubce.com"
    ]
}
EOF

    # 重启 Docker 服务
    systemctl daemon-reload
    systemctl restart docker
    
    # 等待 Docker 服务就绪
    echo -e "${YELLOW}等待 Docker 服务就绪...${NC}"
    for i in {1..30}; do
        if docker info &> /dev/null; then
            echo -e "${GREEN}Docker 服务已就绪${NC}"
            break
        fi
        echo -n "."
        sleep 1
    done
fi
show_progress 100

# 输入QQ号
echo -e "\n${CYAN}[2/5]${NC} 配置QQ账号..."

# 确保终端处于正确的状态
stty sane

# 清理任何可能的输入缓存
read -t 1 -n 10000 discard 2>/dev/null || true

# 在同一行显示提示并等待输入
while true; do
    # 使用 /dev/tty 直接从终端读取输入
    exec 3</dev/tty
    printf "${CYAN}请输入QQ号: ${NC}" >/dev/tty
    read -r QQ_ACCOUNT <&3
    exec 3<&-
    
    # 验证输入
    if [[ "$QQ_ACCOUNT" =~ ^[1-9][0-9]{4,11}$ ]]; then
        printf "${GREEN}QQ号格式正确！${NC}\n" >/dev/tty
        break
    else
        printf "${RED}错误：请输入正确的QQ号（5-12位数字）${NC}\n" >/dev/tty
    fi
done

# 显示进度
show_progress 50

# 配置 Docker 镜像加速器
echo -e "\n${CYAN}[3/5]${NC} 配置 Docker 加速器..."
mkdir -p /etc/docker
cat > /etc/docker/daemon.json <<EOF
{
    "registry-mirrors": [
        "https://docker.1ms.run",
        "https://mirror.ccs.tencentyun.com",
        "https://hub-mirror.c.163.com",
        "https://mirror.baidubce.com"
    ],
    "dns": ["223.5.5.5", "223.6.6.6", "8.8.8.8"],
    "max-concurrent-downloads": 10,
    "max-concurrent-uploads": 5,
    "log-driver": "json-file",
    "log-opts": {
        "max-size": "100m",
        "max-file": "3"
    }
}
EOF

# 重启 Docker 服务
systemctl daemon-reload
systemctl restart docker
show_progress 100

# 创建 Docker 网络（如果不存在）
echo -e "\n${CYAN}[4/5]${NC} 配置网络环境..."
if ! docker network inspect astrbot_default >/dev/null 2>&1; then
    docker network create astrbot_default
fi
show_progress 100

# 启动容器
echo -e "\n${CYAN}[5/5]${NC} 启动 Napcat 容器..."
if docker ps -a | grep -q "napcat"; then
    docker rm -f napcat
fi

# 尝试拉取镜像
echo -e "${YELLOW}正在拉取镜像...${NC}"
if ! docker pull mlikiowa/napcat-docker:latest; then
    echo -e "${RED}错误：无法拉取镜像。请检查网络连接或稍后重试。${NC}"
    exit 1
fi

# 运行容器并检查是否成功
if ! docker run -d \
    -e ACCOUNT="$QQ_ACCOUNT" \
    -e WS_ENABLE=true \
    -e NAPCAT_GID=0 \
    -e NAPCAT_UID=0 \
    -p 3001:3001 \
    -p 6099:6099 \
    --name napcat \
    --network=astrbot_default \
    --restart=always \
    mlikiowa/napcat-docker:latest; then
    
    echo -e "${RED}错误：容器启动失败。${NC}"
    exit 1
fi

# 等待容器启动
sleep 3

# 获取容器ID
CONTAINER_ID=$(docker ps -q -f name=napcat)

# 配置文件
echo -e "\n${CYAN}正在配置文件...${NC}"
CONFIG_FILE="/napcat/config/napcat_${QQ_ACCOUNT}.json"
docker exec -i "$CONTAINER_ID" /bin/bash -c "cat > $CONFIG_FILE" << EOF
{
  "network": {
    "httpServers": [],
    "httpSseServers": [],
    "httpClients": [],
    "websocketServers": [],
    "websocketClients": [
      {
        "enable": true,
        "name": "默认",
        "url": "ws://${SERVER_IP}:6199/ws",
        "reportSelfMessage": false,
        "messagePostFormat": "array",
        "token": "",
        "debug": false,
        "heartInterval": 30000,
        "reconnectInterval": 30000
      }
    ],
    "plugins": []
  },
  "musicSignUrl": "",
  "enableLocalFile2Url": false,
  "parseMultMsg": true
}
EOF

# 获取WebUI Token
echo -e "${YELLOW}尝试获取 WebUI Token...${NC}"
WEBUI_TOKEN=""

# 首先尝试从容器中读取
if ! WEBUI_TOKEN=$(docker exec -i "$CONTAINER_ID" /bin/bash -c "cat /napcat/config/webui.json" 2>/dev/null | grep -o '"token": "[^"]*"' | cut -d'"' -f4); then
    echo -e "${YELLOW}无法从默认位置读取 WebUI Token，尝试创建新配置...${NC}"
    
    # 创建完整的 webui.json
    docker exec -i "$CONTAINER_ID" /bin/bash -c "cat > /napcat/config/webui.json" << EOF
{
    "port": 6099,
    "host": "0.0.0.0",
    "token": "napcat",
    "timeout": 3600000
}
EOF
    
    WEBUI_TOKEN="napcat"
    echo -e "${GREEN}已创建新的 WebUI 配置${NC}"
fi

# 如果还是获取不到，提供可能的配置文件位置
if [ -z "$WEBUI_TOKEN" ]; then
    echo -e "${YELLOW}注意：WebUI Token 获取失败${NC}"
    echo -e "请检查以下位置的配置文件："
    echo -e "1. 容器内路径：/napcat/config/webui.json"
    echo -e "2. 映射路径：./data/config/webui.json"
    echo -e "3. 容器数据卷：$(docker inspect napcat | grep Source | grep config || echo '未找到数据卷')"
    WEBUI_TOKEN="napcat"
fi

# 获取本地IP
LOCAL_IP=$(ip addr show | grep -w inet | grep -v 127.0.0.1 | awk '{print $2}' | cut -d/ -f1)

# 如果本地IP以17开头，直接使用
if echo "$LOCAL_IP" | grep -q "^17"; then
    SERVER_IP=$LOCAL_IP
else
    # 否则获取本地IP的第三段
    LOCAL_IP=$(echo "$LOCAL_IP" | grep ^192)
    SUBNET=$(echo "$LOCAL_IP" | cut -d. -f3)
    # 查找对应的 17X.${SUBNET} 开头的IP
    SERVER_IP=$(ifconfig | grep -B1 "inet 17" | grep inet | awk '{print $2}' | grep "^17.*\.${SUBNET}\.")
fi

# 显示完成界面
clear
echo -e "${GREEN}${BOLD}"
cat << "EOF"
✨ 部署完成！Napcat 已成功启动 ✨
EOF
echo -e "${NC}"

echo -e "${CYAN}==================================${NC}"
echo -e "${BOLD}服务信息：${NC}"
echo -e "${BLUE}▶ QQ账号：${QQ_ACCOUNT}${NC}"
echo -e "${BLUE}▶ WebSocket地址：ws://${SERVER_IP}:6099${NC}"
echo -e "${BLUE}▶ HTTP接口地址：http://${SERVER_IP}:3001${NC}"
echo -e "${BLUE}▶ WebUI地址：http://${SERVER_IP}:6099/webui/${NC}"
echo -e "${BLUE}▶ WebUI Token：${WEBUI_TOKEN}${NC}"
echo -e "${CYAN}==================================${NC}"

echo -e "\n${GREEN}服务状态：${NC}"
docker ps | grep napcat

echo -e "\n${YELLOW}提示：${NC}"
echo -e "1. 如需查看日志，请使用命令：${BOLD}docker logs -f napcat${NC}"
echo -e "2. 如需停止服务，请使用命令：${BOLD}docker stop napcat${NC}"
echo -e "3. 如需重启服务，请使用命令：${BOLD}docker restart napcat${NC}"
echo -e "4. 如需进入容器，请使用命令：${BOLD}docker exec -it napcat /bin/bash${NC}"
echo -e "5. 配置文件路径：${BOLD}/napcat/config/napcat_${QQ_ACCOUNT}.json${NC}"

exit 0 